import { defineStore } from 'pinia'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    role: null, // 'user' | 'doctor' | 'admin'
    user: null,
  }),
  getters: {
    isLoggedIn: (s) => !!s.role,
    currentId: (s) => {
      if (!s.user) return null
      return s.user.userId || s.user.doctorId || s.user.adminId || s.user.id || null
    }
  },
  actions: {
    setRoleAndUser(role, user) {
      this.role = role
      this.user = user
      localStorage.setItem('auth', JSON.stringify({ role, user }))
    },
    initFromStorage() {
      const raw = localStorage.getItem('auth')
      if (raw) {
        try {
          const obj = JSON.parse(raw)
          this.role = obj.role
          this.user = obj.user
        } catch (e) {
          console.warn('auth storage parse failed')
        }
      }
    },
    logout() {
      this.role = null
      this.user = null
      localStorage.removeItem('auth')
    }
  }
})